/*
 * Created by Jaren at 2021/8/24 15:44
 */
import 'dart:typed_data';

import 'package:inmotion_protocol/base/base_message.dart';
import 'package:inmotion_protocol/base/codec.dart';

class CodecHolder {
  CodecHolder._privateConstructor();

  static final CodecHolder _instance = CodecHolder._privateConstructor();

  static CodecHolder get instance => _instance;

  Map<String, Encoder> encoders = {};
  Map<String, Decoder> decoders = {};

  Uint8ClampedList encode<T extends IMessage>(T msg, [String clientId = '']) {
    return _encoder(clientId).encode(msg);
  }

  List<T> decode<T extends IMessage>(Uint8ClampedList bytes, List<T> output, [String clientId = '']) {
    return _decoder(clientId).decode(bytes, output);
  }

  dynamic _encoder([String clientId = '']) {
    Encoder? encoder = encoders[clientId];
    if (encoder == null) throw Exception('No encoder found for client $clientId');
    return encoder;
  }

  dynamic _decoder<T extends IMessage>([String clientId = '']) {
    Decoder? decoder = decoders[clientId];
    if (decoder == null) throw Exception('No decoder found for client $clientId');
    return decoder;
  }

  Encoder putEncoder(Encoder encoder, [String clientId = '']) {
    encoders[clientId] = encoder;
    return encoder;
  }

  Decoder putDecoder(Decoder decoder, [String clientId = '']) {
    decoders[clientId] = decoder;
    return decoder;
  }
}
